package ysq.xyg.recovery.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.iherus.codegen.qrcode.SimpleQrcodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import ysq.xyg.base.model.dto.ReturnEntity;
import ysq.xyg.base.service.impl.BaseServiceImpl;
import ysq.xyg.base.util.BaseConstant;
import ysq.xyg.base.util.httpClient.HttpUtil;
import ysq.xyg.recovery.dao.RecoverySackDao;
import ysq.xyg.recovery.model.po.RecoverySack;
import ysq.xyg.recovery.model.vo.RecoverySackVo;
import ysq.xyg.recovery.service.RecoverySackService;
import ysq.xyg.sys.model.po.SysUser;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Date;
import java.util.List;

/**
 * 回收金模块-袋子service实现
 *
 * @author congcong tao
 * @date 2019-7-8 14:45:11
 */
@Service("recoverySackService")
public class RecoverySackServiceImpl extends BaseServiceImpl<RecoverySack> implements RecoverySackService {

    @Resource
    private RecoverySackDao recoverySackDao;

    private RecoverySack recoverySack;

    @Autowired
    public void setBaseDao(RecoverySackDao recoverySackDao) {
        this.baseDao = recoverySackDao;
    }

    /**
     * 分页查询
     *
     * @param recoverySackVo 对象
     * @param pageSize 展示数量
     * @param pageNum 当前页面
     * @return ReturnEntity 对象
     * @author congcong tao
     * @date 2019-7-8 14:45:11
     */
    @Override
    public ReturnEntity page(RecoverySackVo recoverySackVo, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        PageHelper.orderBy(" create_time desc");
        List<RecoverySack> list = acceptList(recoverySackVo);
        PageInfo<RecoverySack> page=new PageInfo<RecoverySack>(list);
        return new ReturnEntity(page.getList(),page.getTotal(),page.isHasNextPage());
    }

    /**
     * 修改
     *
     * @param recoverySackVo 对象
     * @param currentUser 当前用户
     * @return ReturnEntity 对象
     * @author congcong tao
     * @date 2019-7-8 14:45:11
     */
    @Override
    public ReturnEntity addOrUpdate(HttpServletRequest request, RecoverySackVo recoverySackVo, SysUser currentUser) {
        boolean isUpate=true;
        Boolean flag = checkSackByCardNo(recoverySackVo.getId(), recoverySackVo.getCardNo());
        if (!flag) {
            return new ReturnEntity(BaseConstant.FAIL, "编号重复，请重新确认");
        }
        if (StrUtil.isEmpty(recoverySackVo.getId())) {
            // 判断是否存在该编号
            recoverySack = new RecoverySack(currentUser);
            if (StringUtils.isEmpty(recoverySackVo.getStatus())) {
                recoverySack.setStatus(BaseConstant.RECOVERY_SACK_STATUS_UNUSED);
            }
            isUpate=false;
        } else {
            recoverySack = selectByPrimaryKey(recoverySackVo.getId());
            if(ObjectUtil.isNull(recoverySack)){
                return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
            }
            recoverySack.setStatus(recoverySackVo.getStatus());
            recoverySack.setUpdateTime(new Date());
            recoverySack.setUpdateUser(currentUser.getId());
        }
        recoverySack.setCardNo(recoverySackVo.getCardNo());
        /*// 编号图片
        String realPath = HttpUtil.getRealPath(request);
        // 如果文件夹不存在则创建
        File dicFile = new File(realPath+"/upload/recoverysack/");
        if  (!dicFile .exists()  && !dicFile .isDirectory()) {
            dicFile .mkdir();
        }
        try {
            // WebAccount webAccount = WxMemoryCacheClient.getSingleWxAccountInfo();
            // String url = webAccount.getBaseUrl() + ProProperties.getInstance().getRecoverySackQrCodeScanUrl() + recoverySackVo.getCardNo();
            String path = realPath+"/upload/recoverysack/" + recoverySackVo.getCardNo() + ".png";
            OutputStream out = new FileOutputStream(path);
            new SimpleQrcodeGenerator().generate(recoverySackVo.getCardNo()).toStream(out);
            recoverySack.setQrImage("/upload/recoverysack/" + recoverySackVo.getCardNo() + ".png");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }*/

        int num = 0;
        if (isUpate) {
            num = updateByPrimaryKeySelective(recoverySack);
        }else{
            num=insert(recoverySack);
        }
        if(num<=0){
            return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
        }
        return new ReturnEntity();
    }

    private Boolean checkSackByCardNo(String id, String cardNo) {
        RecoverySackVo recoverySackVo = new RecoverySackVo();
        recoverySackVo.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_NORMAL);
        recoverySackVo.setCardNo(cardNo);
        List<RecoverySack> recoverySacks = acceptList(recoverySackVo);
        if (StringUtils.isEmpty(id)) {
            if (recoverySacks != null && recoverySacks.size() > 0) {
                return Boolean.FALSE;
            }
            return Boolean.TRUE;
        } else {
            if (recoverySacks == null || recoverySacks.size() == 0) {
                return Boolean.TRUE;
            }
            RecoverySack recoverySack = selectByPrimaryKey(id);
            RecoverySack entity = recoverySacks.get(0);
            if (!StringUtils.equals(entity.getId(), recoverySack.getId()) && StringUtils.equals(entity.getCardNo(), cardNo)) {
                return Boolean.FALSE;
            } else {
                return Boolean.TRUE;
            }
        }
    }

    /**
     * 删除
     *
     * @param id 主键id
     * @param currentUser 当前用户
     * @return ReturnEntity 对象
     * @author congcong tao
     * @date 2019-7-8 14:45:11
     */
    @Override
    public ReturnEntity delete(String id, SysUser currentUser) {
        RecoverySack recoverySack=selectByPrimaryKey(id);
        if(recoverySack!=null){
            recoverySack.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_DELETE);
            recoverySack.setUpdateTime(new Date());
            recoverySack.setUpdateUser(currentUser.getId());
            int num=updateByPrimaryKey(recoverySack);
            if(num>0){
                return new ReturnEntity();
            }
        }
        return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
    }

    /**
     * 获取集合
     *
     * @param recoverySackVo 对象
     * @return List<BaseDict> BaseDict集合
     * @author congcong tao
     * @date 2019-7-8 14:45:11
     */
    @Override
    public List<RecoverySack> acceptList(RecoverySackVo recoverySackVo){
        Example example = new Example(RecoverySack.class);
        Example.Criteria criteria = example.createCriteria();
        if(StringUtil.isNotEmpty(recoverySackVo.getRemoveTag())){
            criteria.andEqualTo("removeTag",recoverySackVo.getRemoveTag());
        }
        if(StringUtil.isNotEmpty(recoverySackVo.getCardNo())){
            criteria.andEqualTo("cardNo",recoverySackVo.getCardNo());
        }
        example.setOrderByClause(" update_time desc");
        return recoverySackDao.selectByExample(example);
    }
}
